﻿using System.Collections.Generic;
using Cubicle.Core.Interfaces;
using Cubicle.Core.Shared;

namespace Cubicle.Core.Repository.HandleParsers
{
    public class HandleRegister : IHandleRegister
    {

        protected Dictionary<char, IHandleParser> _parsers = new Dictionary<char, IHandleParser>();

        public IHandleParser DefaultParserBase { get; protected set; }
        public IHandleParser NullParserBase { get; protected set; }
        public IHandleParser EmptyParserBase { get; protected set; }

        public HandleRegister(
            IHandleParser defaultParserBase, 
            IHandleParser nullParserBase,
            IHandleParser emptyParserBase,
            IEnumerable<IHandleParser> parsers = null)
        {
            DefaultParserBase = defaultParserBase;
            NullParserBase = nullParserBase;
            EmptyParserBase = emptyParserBase;
            if (parsers != null)
                parsers.Iter(x => _parsers.Add(x.Prefix, x));
        }

        public void Register(IHandleParser parserBase)
        {
            _parsers[parserBase.Prefix] = parserBase;
        }

        public IEnumerable<IHandleParser> ListParsers()
        {
            return _parsers.Values;
        }

        public IHandleParser KeyToParser(string key)
        {
            if (key == string.Empty) return EmptyParserBase;
            if (key == null || key[0] == NullParserBase.Prefix) return NullParserBase;
            if (key[0] == EmptyParserBase.Prefix) return EmptyParserBase;
            IHandleParser result = null;
            _parsers.TryGetValue(key[0], out result);
            return result ?? DefaultParserBase;
        }

        public string KeyToHandle(string key)
        {
            return KeyToParser(key).KeyToHandle(key);
        }
    }

}
